package com.rzj.book.handleType;

import com.rzj.book.en.Dep;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description:
 * @author: rzj
 * @time: 2020/5/27 22:25
 */
public class DepTypeHandler extends BaseTypeHandler<Dep> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Dep dep, JdbcType jdbcType) throws SQLException {
        if (dep == null) return;
        Long depId = dep.getDepId();

        StringBuilder builder = new StringBuilder();

        builder.append(depId);
        ps.setString(i, builder.toString());
    }

    @Override
    public Dep getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (columnValue.isEmpty() || !columnValue.contains(",")) {
            return null;
        }

        String[] split = columnValue.split(",");

        Long depId = Long.valueOf(split[0]);
        String name = split[1];
        String tele = split[2];

        Dep dep = new Dep(depId, name, tele);
        return dep;
    }

    @Override
    public Dep getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (columnValue.isEmpty() || !columnValue.contains(",")) {
            return null;
        }

        String[] split = columnValue.split(",");

        Long depId = Long.valueOf(split[0]);
        String name = split[1];
        String tele = split[2];

        Dep dep = new Dep(depId, name, tele);
        return dep;
    }

    @Override
    public Dep getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (columnValue.isEmpty() || !columnValue.contains(",")) {
            return null;
        }

        String[] split = columnValue.split(",");

        Long depId = Long.valueOf(split[0]);
        String name = split[1];
        String tele = split[2];

        Dep dep = new Dep(depId, name, tele);
        return dep;
    }
}
